import sys
import os as os_module
sys.path.append(os_module.path.dirname(os_module.path.dirname(os_module.path.abspath(__file__))))
from logger import get_module_logger
logger = get_module_logger('switch_directory')

from flask import current_app
from flask import Blueprint,  request, jsonify,render_template,session
from bt import Bt_api
from decorator import login_required
# 移除缓存导入，因为我们不再使用缓存
import os
blueprint = Blueprint('/switch_directory', __name__, url_prefix='/switch_directory')

@blueprint.route("/", endpoint='/', methods=['GET', 'POST'])
@login_required
def switch_directory():
    if request.method == 'POST':
        # 移除缓存相关代码，直接从宝塔API获取数据
        
        # 实例化宝塔API对象
        bt_api=Bt_api(session.get('bt_url'),session.get('bt_key'))
        data = bt_api.GetDirUserINI(session.get('siteId'),session.get('bt_fife'))
        
        # 获取网站根目录
        site_path = session.get('bt_fife')
        
        # 获取目录列表
        dirs = []
        if os.path.exists(site_path):
            try:
                for item in os.listdir(site_path):
                    item_path = os.path.join(site_path, item)
                    if os.path.isdir(item_path):
                        dirs.append(item)
            except Exception as e:
                logger.error(f"Error reading directory: {e}")
        
        # 返回完整的数据结构
        result = {
            'dirs': dirs,
            'runPath': data.get('runPath', '') if isinstance(data, dict) else ''
        }
        
        # 移除缓存存储代码，直接返回数据
        return jsonify(result)
    cdn=current_app.config['CDN']
        

    return render_template('switch_directory.html',cdn=cdn)
    
@blueprint.route("SetSiteRunPath", endpoint='SetSiteRunPath', methods=['GET', 'POST'])
@login_required
def SetSiteRunPath():
    if request.method == 'POST':
        runPath=request.form.get('runPath')
        # 实例化宝塔API对象
        bt_api=Bt_api(session.get('bt_url'),session.get('bt_key'))
        data = bt_api.SetSiteRunPath(session.get('siteId'),runPath)
        
        # 移除缓存删除代码，因为我们不再使用缓存
        
        return jsonify(data)
    cdn=current_app.config['CDN']
        

    return render_template('switch_directory.html',cdn=cdn)